import express from 'express'
// Global Async Exception Capture
import 'express-async-errors';
import cors from 'cors';
import { getLocalIP, errorHandler } from './common/utils.js';
import routers from './routes/index.js';
import 'dotenv/config';
import { authenticateToken } from './common/auth.js';
import path from 'path';
import { fileURLToPath } from 'url';

const app = express();
const port = process.env.PORT || 88;


// CORS 配置
const corsOptions = {
  origin: true,
  credentials: true
};

// 使用 CORS 中间件
app.use(cors(corsOptions));

// 使用JSON解析中间件
app.use(express.json());

// 全局应用鉴权中间件
app.use(authenticateToken);

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, './uploads')));

// 挂载所有路由
routers.forEach(router => app.use('/api',router));

// 统一异常捕获
app.use(errorHandler);



// 启动服务器
app.listen(port, () => {
  console.log(`====================================`);
  console.log(`UniHub backend server is start!`);
  console.log(`Server is running on \n http://127.0.0.1:${port} \n http://${getLocalIP()}:${port}`);
  console.log(`====================================`);
});

export default app;
